package com.zch.socket.aio.server2;

import com.zch.socket.common.ByteUtils;
import com.zch.socket.common.model.RequestModel;
import com.zch.socket.common.model.ResponseModel;
import sun.misc.Request;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class ServerReadHandler implements CompletionHandler<Integer,ByteBuffer> {
    private AsynchronousSocketChannel channel;

    public ServerReadHandler(AsynchronousSocketChannel channel) {
        this.channel = channel;
    }

    /**

     * 读取到消息后处理
     * @param result
     * @param attachment
     */
    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        RequestModel requestModel= (RequestModel) ByteUtils.ByteBufferToObject(attachment);
        Object[] str=requestModel.getParams();
        String s=(String) str[0];
        System.out.println("成功接收到客户的数据: "+s);

           ByteBuffer writerBuffer = ByteBuffer.allocate(1024);
        ResponseModel responseModel=new ResponseModel();
         responseModel.setStr("我是服务端返回");
         writerBuffer=ByteUtils.ObjectToByteBuffer(writerBuffer,responseModel);
           channel.write(writerBuffer,writerBuffer,new ServerWriterHandler(channel));

    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
       System.out.println("读取客户端异常");
       exc.printStackTrace();
       //出现异常显示的关闭通道，aio的通道是不会主动关闭的，可以理解为可复用的长连接。
        try {
            channel.close();
        } catch (IOException e) {
        }
    }
}
